import time

import psutil
import win32con
import win32gui
import win32process
import subprocess


class Process:
    process_info_list = list

    def __init__(self):
        self.update()

    def update(self):
        proc, all_processes = [], psutil.process_iter()
        for items in all_processes:
            try:
                procinfo = items.as_dict(attrs=["pid", "name"])
                try:
                    # the process start path
                    p_path_cwd = items.cwd().decode("gbk")

                    # the process accounts for system memory uasge
                    proc_mem_percent = items.memory_percent()

                    # the process starts cmdline content
                    cmdlines = str(items.cmdline())

                    # the process accounts for system CPU usage
                    cpu_percent = items.cpu_percent(interval=1)
                except Exception as e:
                    try:
                        p_path_cwd = items.exe()
                    except Exception as e:
                        p_path_cwd = e.name
                p_status, p_create_time, proc_user, proc_io_info = items.status(), items.create_time(), items.username(), {}

                try:
                    proc_io = items.io_counters()
                    proc_io_info["ReadCount"] = proc_io.read_count
                    proc_io_info["WriteCount"] = proc_io.write_count
                    proc_io_info["ReadBytes"] = proc_io.read_bytes
                    proc_io_info["WriteBytes"] = proc_io.write_bytes
                except Exception:
                    pass
                procinfo.update({"path": p_path_cwd,
                                 "cmdline": cmdlines,
                                 "cpu_percent": cpu_percent,
                                 "status": p_status,
                                 "CreateTime": p_create_time,
                                 "MemPercent": proc_mem_percent,
                                 "user": proc_user,
                                 "DiskIo": proc_io_info})
            except Exception:
                pass
            finally:
                proc.append(procinfo)
        self.process_info_list = proc

    def getProcessInfo(self, name):
        pi = self.process_info_list
        for item in pi:
            if item["name"] == name:
                return item
        return None

    def get_hwnds_for_pid(self, pid):
        # 通过PID查询句柄ID
        def callback(hwnd, hwnds):
            if win32gui.IsWindowVisible(hwnd) and win32gui.IsWindowEnabled(hwnd):
                _, found_pid = win32process.GetWindowThreadProcessId(hwnd)
                if found_pid == pid:
                    hwnds.append(hwnd)
                return True

        hwnds = []
        win32gui.EnumWindows(callback, hwnds)
        hwndy = 0
        if hwnds:
            hwndy = hwnds[0]

        return hwndy

    def isRun(self, name):
        pi = self.process_info_list
        for item in pi:
            if item["name"] == name:
                return True
        return False

    def openProcess(self, path):
        subprocess.Popen(path, shell=True, stdout=subprocess.PIPE)
        print("打开投屏软件", path, "，连接到手机！")
        time.sleep(5)
        self.update()
        print("更新进程列表完成！")

    def getScrcpyProLocation(self, hnd):
        # 获取窗口左上角坐标和右下角坐标
        return win32gui.GetWindowRect(hnd)

    def showWindow(self, hnd):
        win32gui.SetForegroundWindow(hnd)
        win32gui.ShowWindow(hnd, win32con.SW_NORMAL)

    def hideWindow(self, hnd):
        win32gui.SetForegroundWindow(hnd)
        win32gui.ShowWindow(hnd, win32con.HIDE_WINDOW)
